package schema

import (
	"time"

	"entgo.io/ent"
	"entgo.io/ent/schema/edge"
	"entgo.io/ent/schema/field"
	"entgo.io/ent/schema/index"
)

// Message holds the schema definition for the Message entity.
type Message struct {
	ent.Schema
}

// Fields of the Message.
func (Message) Fields() []ent.Field {
	return []ent.Field{
		field.Int64("id").
			Positive().
			Unique().
			Immutable().
			Comment("消息ID"),
		field.Int64("conversation_id").
			Comment("会话ID"),
		field.Int64("sender_id").
			Comment("发送者ID"),
		field.Text("content").
			Optional().
			Comment("消息内容"),
		field.Enum("content_type").
			Values("text", "image", "file", "audio", "video", "location", "system").
			Default("text").
			Comment("内容类型"),
		field.String("file_url").
			Optional().
			MaxLen(255).
			Comment("文件URL"),
		field.String("file_name").
			Optional().
			MaxLen(255).
			Comment("文件名"),
		field.Int64("file_size").
			Optional().
			Comment("文件大小"),
		field.Bool("is_edited").
			Default(false).
			Comment("是否已编辑"),
		field.Bool("is_deleted").
			Default(false).
			Comment("是否已删除"),
		field.Int64("reply_to_id").
			Optional().
			Comment("回复消息ID"),
		field.Time("created_at").
			Default(time.Now).
			Immutable().
			Comment("创建时间"),
		field.Time("updated_at").
			Default(time.Now).
			UpdateDefault(time.Now).
			Comment("更新时间"),
	}
}

// Edges of the Message.
func (Message) Edges() []ent.Edge {
	return []ent.Edge{
		edge.From("conversation", Conversation.Type).
			Ref("messages").
			Field("conversation_id").
			Unique().
			Required().
			Comment("所属会话"),
		edge.From("sender", User.Type).
			Ref("sent_messages").
			Field("sender_id").
			Unique().
			Required().
			Comment("发送者"),
		edge.From("reply_to", Message.Type).
			Ref("replies").
			Field("reply_to_id").
			Unique().
			Comment("回复的消息"),
		edge.To("replies", Message.Type).
			Comment("回复"),
		edge.To("read_statuses", MessageReadStatus.Type).
			Comment("已读状态"),
		edge.To("read_by_members", ConversationMember.Type).
			Comment("已读此消息的成员"),
	}
}

// Indexes of the Message.
func (Message) Indexes() []ent.Index {
	return []ent.Index{
		index.Fields("conversation_id"),
		index.Fields("sender_id"),
		index.Fields("reply_to_id"),
		index.Fields("created_at"),
	}
}
